package org.xiaoyu.rpc.registry.zookeeper;

import org.xiaoyu.rpc.common.url.URL;
import org.xiaoyu.rpc.registry.Discover;

import java.util.ArrayList;
import java.util.List;

/**
 * Created By Have
 * 2021/7/14 22:56
 */
public class ZookeeperDiscover implements Discover {
    private ZookeeperInstanceWrapper zkClient;

    public ZookeeperDiscover(ZookeeperInstanceWrapper zkClient) {
        this.zkClient = zkClient;
    }

    @Override
    public List<URL> lookupService(URL url) {
        List<String> result = zkClient.lookup(url);
        List<URL> findService = new ArrayList<>();
        for (String address : result) {
            String[] split = address.split(":");
            URL service = URL.builder()
                    .serviceName(url.getServiceName())
                    .version(url.getVersion())
                    .group(url.getGroup())
                    .weight(url.getWeight())
                    .path(url.getPath())
                    .host(split[0])
                    .port(Integer.valueOf(split[1]))
                    .build();
            findService.add(service);
        }
        return findService;
    }
}
